package com.godme.controller;


import com.godme.bean.Person;
import com.godme.repo.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
public class PersonController {


    @Autowired
    PersonRepository personRepository;

    @GetMapping("/all")
    public List<Person> searchAll(){
        return personRepository.findAll();
    }

    @GetMapping("/add/{name}")
    public String addPerson(@PathVariable("name")String name){
        Person person = new Person();
        person.setName(name);
        personRepository.save(person);
        return person.getName();
    }

    @GetMapping("/delete/{id}")
    public void delete(@PathVariable("id")Integer id){
        personRepository.deleteById(id);
    }

    @GetMapping("/update/{id}/{name}")
    public void update(@PathVariable("id") Integer id, @PathVariable("name") String name){
        Optional<Person> optional = personRepository.findById(id);
        Person person = optional.orElseGet(Person::new);
        person.setName(name);
        personRepository.save(person);
    }


}
